# PowerShell云服务器自动更新脚本（优化版）
# 注意：1. 需要管理员权限 2. 首次运行前设置执行策略：Set-ExecutionPolicy RemoteSigned

$ErrorActionPreference = "Stop"  # 遇到错误立即停止
$venvPath = "C:\VISION_HEALTH\.venv"  # 虚拟环境路径
$projectPath = "C:\VISION_HEALTH"    # 项目路径

try {
    Write-Host "=== 开始更新生产环境 ===" -ForegroundColor Green
    
    # 1. 切换到项目目录
    Set-Location $projectPath
    Write-Host "当前目录: $(Get-Location)" -ForegroundColor Cyan

    # 2. 创建备份分支
    $backupBranch = "backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    git branch $backupBranch
    Write-Host "已创建备份分支: $backupBranch" -ForegroundColor Cyan

    # 3. 获取最新代码
    Write-Host "拉取最新代码..." -ForegroundColor Cyan
    git fetch origin
    git checkout main
    git reset --hard origin/main
    Write-Host "当前提交: $(git rev-parse --short HEAD)" -ForegroundColor Cyan

    # 4. 激活虚拟环境（关键步骤）
    Write-Host "激活虚拟环境..." -ForegroundColor Cyan
    if (Test-Path "$venvPath\Scripts\Activate.ps1") {
        & "$venvPath\Scripts\Activate.ps1"
        $pythonPath = (Get-Command python).Source
        Write-Host "虚拟环境已激活: $pythonPath" -ForegroundColor Cyan
    } else {
        throw "虚拟环境激活文件未找到: $venvPath\Scripts\Activate.ps1"
    }

    # 5. 更新依赖（将在虚拟环境中安装）
    Write-Host "更新依赖..." -ForegroundColor Cyan
    pip install -r requirements.txt --upgrade
    Write-Host "依赖已更新" -ForegroundColor Cyan

    # 6. 数据库迁移（修复：使用正确的环境变量）
    Write-Host "执行数据库迁移..." -ForegroundColor Cyan
    $env:FLASK_APP = "backend"
    flask db upgrade
    Write-Host "数据库迁移完成" -ForegroundColor Cyan

    # 7. 停止现有服务进程（如果存在）
    Write-Host "停止现有服务进程..." -ForegroundColor Cyan
    Get-Process -Name "python" -ErrorAction SilentlyContinue | Where-Object {$_.CommandLine -like "*waitress*" -or $_.CommandLine -like "*app.py*"} | Stop-Process -Force
    Start-Sleep -Seconds 3
    Write-Host "现有服务进程已停止" -ForegroundColor Cyan

    # 8. 启动新服务
    Write-Host "启动生产服务..." -ForegroundColor Cyan
    Start-Process -FilePath "powershell.exe" -ArgumentList "-File", ".\run_production_en.ps1" -WindowStyle Minimized
    Start-Sleep -Seconds 5
    
    # 9. 验证服务启动
    Write-Host "验证服务启动..." -ForegroundColor Cyan
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:5000" -Method Get -TimeoutSec 10
        if ($response.StatusCode -eq 200) {
            Write-Host "✅ 服务启动成功，状态码: $($response.StatusCode)" -ForegroundColor Green
        }
    } catch {
        Write-Host "⚠️ 服务启动验证失败，请手动检查" -ForegroundColor Yellow
    }

    Write-Host "=== 更新成功完成 ===" -ForegroundColor Green
    Write-Host "备份分支: $backupBranch" -ForegroundColor Green
    Write-Host "服务地址: http://localhost:5000" -ForegroundColor Green
    Write-Host "生产脚本: .\run_production_en.ps1" -ForegroundColor Green
}
catch {
    Write-Host "=== 更新失败 ===" -ForegroundColor Red
    Write-Host "错误信息: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请检查错误并手动修复" -ForegroundColor Red
    exit 1
}
    Write-Host "错误: $_" -ForegroundColor Red
    exit 1
}